package com.hzdesk.media.koreabatchmatvector.fragment.fragment_persenter;

import android.content.Context;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hzdesk.media.koreabatchmatvector.adapter.CloudListAdapter;
import com.hzdesk.media.koreabatchmatvector.bean.DwonloadFileUrlBean;
import com.hzdesk.media.koreabatchmatvector.base.MyClientApplication;
import com.hzdesk.media.koreabatchmatvector.bean.CloudListBean;
import com.hzdesk.media.koreabatchmatvector.bean.DeviceAttributeBean;
import com.hzdesk.media.koreabatchmatvector.bean.Memory;
import com.hzdesk.media.koreabatchmatvector.bean.VideoFile;
import com.hzdesk.media.koreabatchmatvector.config.RBConfig;
import com.hzdesk.media.koreabatchmatvector.custom.MyItemDecoration;
import com.hzdesk.media.koreabatchmatvector.dao.DeviceAttributeBeanDaoUtils;
import com.hzdesk.media.koreabatchmatvector.dao.MemoryDaoUtils;
import com.hzdesk.media.koreabatchmatvector.dao.VideoFileDaoUtils;
import com.hzdesk.media.koreabatchmatvector.dialog.DeleteFileDialog;
import com.hzdesk.media.koreabatchmatvector.fragment.fragment_contract.CloudListContract;
import com.hzdesk.media.koreabatchmatvector.inter.ICloudListListenter;
import com.hzdesk.media.koreabatchmatvector.inter.IDeleteFileDialogListener;
import com.hzdesk.media.koreabatchmatvector.inter.IDownloadRequestListenter;
import com.hzdesk.media.koreabatchmatvector.inter.NetworkRequestListener;
import com.hzdesk.media.koreabatchmatvector.request.NetworkRequest;
import com.hzdesk.media.koreabatchmatvector.utils.DeleteDirTest;
import com.hzdesk.media.koreabatchmatvector.utils.JsonUitl;
import com.hzdesk.media.koreabatchmatvector.utils.MyToastUtils;


import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import me.zhouzhuo.zzhorizontalprogressbar.ZzHorizontalProgressBar;
import okhttp3.Response;

/**
 * Created by Administrator on 2018/6/22.
 * 杭州席媒科技有限公司  Developers  刘传华  21
 * 佛祖镇楼 bug辟易
 */

public class CloudListPersenter implements CloudListContract.ICloudListPersenter {

    private String TAG = CloudListPersenter.class.getSimpleName();
    private CloudListContract.ICloudListView iCloudListView;
    private int pager = 1;
    private List<CloudListBean.RowsBean> mlist = new ArrayList<>();
    private NetworkRequest mNetworkRequest;
    private CloudListAdapter mCloudListAdapter;
    private boolean flage = true;
    private int mpostion = 0;
    private RecyclerView xRecyclerView;
    private Context nmcontext;
    int lastVisibleItem;
    boolean isLoading = false;                                                                      //用来控制进入的次数
    int totlePage = 5;                                                                              //模拟请求的一共的页数
    private boolean isitemLoading = false;                                                          //isitemLoading  true 表示正在下载，fase 表示没有item在下载
    int page = 0;
    private NetworkRequest tNetworkRequest;
    private LinearLayoutManager layoutManager;
    private NetworkRequest delectAllfile;
    private boolean isDwonloadFile = true;                                                          // true 可以下载  false 不能下载
    private int downloadfileIndex = 0;                                                              // 下载文件的索引
    private String downloadName;
    private NetworkRequest fileDownload;
    private NetworkRequest fileDownloadUrl;
    private NetworkRequest xmlDownload;
    private double userMemory;

    public CloudListPersenter(CloudListContract.ICloudListView iCloudListView) {
        this.iCloudListView = iCloudListView;
    }

    //todo  初始化  ---------------------------------------------------------------------------------
    @Override
    public void initRecyclerview(final Context mcontext, RecyclerView mXRecyclerView) {
        initDate(mcontext, mXRecyclerView);
        init();
        initListener();
        initRequest();

    }

    //  初始化 数据
    private void initDate(Context mcontext, RecyclerView mXRecyclerView) {
        xRecyclerView = mXRecyclerView;
        nmcontext = mcontext;
        page = 0;
    }

    // 初始化 RecyclerView
    private void init() {
        layoutManager = new LinearLayoutManager(nmcontext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        xRecyclerView.setLayoutManager(layoutManager);
        //添加装饰类
        xRecyclerView.addItemDecoration(new MyItemDecoration());
        mCloudListAdapter = new CloudListAdapter(nmcontext);
        xRecyclerView.setAdapter(mCloudListAdapter);
    }

    // 初始化监听
    private void initListener() {
        xRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                pullLoad(newState);                                                                 //    1
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //拿到最后一个出现的item的位置
                lastVisibleItem = layoutManager.findLastVisibleItemPosition();
            }
        });
        // 点击事件                                                                                  //todo 2,3
        mCloudListAdapter.setmICloudListListenter(new ICloudListListenter() {
            @Override
            public void delectFile(int postion) {
                deleteAmongThemFile(postion);
            }                                                                                       //    2

            @Override
            public void downloadFile(int postion) {
                downFile(postion);
            }
        });
    }


    // 上拉加载                                                                                      //    1
    private void pullLoad(int newState) {
        if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == mCloudListAdapter.getItemCount() && !isLoading) {
            //到达底部之后如果footView的状态不是正在加载的状态,就将 他切换成正在加载的状态
            if (page < totlePage) {
                isLoading = true;
                mCloudListAdapter.changeState(1);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        // 网络加载数据
                        requestCloudList(pager);
                        page++;
                        isLoading = false;
                    }
                }, 500);

            } else {
                mCloudListAdapter.changeState(2);
            }
        }
    }


    //  下载文件 并且确保同一时间只有只能下载一个文件                                                     todo 3
    private void downFile(int postion) {
        CloudListBean.RowsBean bean = mlist.get(postion);
        String file_id = bean.getId();
        // todo 对比内存使用量 在决定有没有空间存放数据和下载
        MemoryDaoUtils memoryDaoUtils = new MemoryDaoUtils(nmcontext);
        Memory memory = memoryDaoUtils.queryTotalSize("TotalSize");
        if(memory != null){
            Memory memoryUserSize =   memoryDaoUtils.queryUserSize("UsedSize");
            if(memoryUserSize != null){
                double remain = memory.getSize() - memoryUserSize.getSize();
                if(remain >= bean.getFileSize()){
                    // 先去查询该本地数据库有没有该文件 file_id
                    VideoFileDaoUtils videoFileDaoUtils = new VideoFileDaoUtils(nmcontext);
                    VideoFile videoFile = videoFileDaoUtils.queryLocalIsVideo(file_id);
                    if (videoFile != null) {
                        //todo 有 就给出提示  在那个文件夹文件 名称
                        MyToastUtils.ShortToaseShow(nmcontext, videoFile.getName() + ".mp4" + "已经存在");
                    } else {
                        Log.e(TAG, "downFile: isDwonloadFile  " +isDwonloadFile);
                        if (isDwonloadFile) {
                            userMemory = memoryUserSize.getSize()+bean.getFileSize();
                            isDwonloadFile = false;
                            downloadfileIndex = postion;
                            downloadName = bean.getName();
                            fileDownloadUrl.requestServerDate(nmcontext, RBConfig.GET_FLE_DOWN_INFO + file_id);
                        }
                    }
                }else{
                    MyToastUtils.ShortToaseShow(nmcontext,"内存空间不足！");
                }

            }else{
                Log.e(TAG, "downFile: 2222" );
            }

        }else {
            Log.e(TAG, "downFile: 1111" );
        }


    }

    private NetworkRequestListener downloadurl = new NetworkRequestListener() {
        @Override
        public void success(Response response) {
            // 解析数据
            //JsonUitl.NetworkResponseDateDeal(response,);
            try {
                String NetWorkResponse = response.body().string();
                JSONObject jsonObject = new JSONObject(NetWorkResponse);
                int Code = JsonUitl.getParsinCode(jsonObject);
                if (Code == 100) {
                    String normalDate = JsonUitl.getStringDateFeld(jsonObject);
                    DwonloadFileUrlBean bean = new Gson().fromJson(normalDate, DwonloadFileUrlBean.class);
                    CloudListBean.RowsBean rowsBean = mlist.get(downloadfileIndex);
                    String Path = DeleteDirTest.getPath("Download/" + rowsBean.getName());
                    // 下载xml
                    String xmlUrl = bean.getBaseUrl() + bean.getXmlSecret();
                    xmlDownload.DownLoadFile(Path, downloadName + ".xml", xmlUrl);
                    // 下载 MP4
                    // 没有就下载
                    // todo path 保存的文件夹和文件名   ------------------------------------> 记得根据返回的正确的路径得到文件名和url
                    String URL = bean.getBaseUrl() + bean.fileSecret;
                    fileDownload.DownLoadFile(Path, downloadName + ".mp4", URL);
                } else {
                    Log.e(TAG, "downFile: Code  " +Code);
                }
            } catch (Exception e) {
            }

        }

        @Override
        public void fail(String s) {

        }
    };

    private IDownloadRequestListenter xmlDownloadfile = new IDownloadRequestListenter() {

        @Override
        public void success(File response, int id) {

        }

        @Override
        public void fail(String s) {

        }

        @Override
        public void Progress(float progress) {

        }
    };
    // 文件下载
    private IDownloadRequestListenter downloadfile = new IDownloadRequestListenter() {
        @Override
        public void success(File response, int id) {
        }

        @Override
        public void fail(String s) {
            isDwonloadFile = true;
        }

        @Override
        public void Progress(float progress) {
            int myprogress = (int)(progress*100);
            upataProgress(myprogress);
        }
    };

    // 更新进度条进度
    private void upataProgress(int progress) {
        CloudListBean.RowsBean bean = mlist.get(downloadfileIndex);
        if (progress < 100) {
            isDwonloadFile = false;
            //  更新进度数据 然后刷新适配器
            bean.setProgress(progress);
            mlist.set(downloadfileIndex, bean);
            mCloudListAdapter.notifyDataSetChanged();
        } else {
            //  当进度到100 后isDwonloadFile要改为true
            isDwonloadFile = true;
            bean.setProgress(progress);
            mlist.set(downloadfileIndex, bean);
            mCloudListAdapter.notifyDataSetChanged();

            String Path = DeleteDirTest.getPath("Download/" + bean.getName());
            //  下载完后在数据库存储对应的 下载文件信息
            VideoFileDaoUtils videoFileDaoUtils = new VideoFileDaoUtils(nmcontext);
            try {
                long size = (long)( bean.getFileSize()*1024*1024);
                String file_id =  bean.getId();
                //  修改Memory数据库的UserSize
                MemoryDaoUtils memoryDaoUtils = new MemoryDaoUtils(nmcontext);
                Memory memory =  new Memory(null,"UsedSize",userMemory);
                memoryDaoUtils.insertUserSize(memory);
                VideoFile videoFile =  new VideoFile(null, bean.getName(), bean.getCreateTime(), Path, size, bean.getName(),bean.getRealName(),false,false,100,file_id,bean.getMeetingGroup(),bean.getMeetingName(),bean.getMeetTime());
                videoFileDaoUtils.queryCreate(file_id, videoFile);
            } catch (NumberFormatException e) {
                Log.e(TAG, "upataProgress: 下载文件信息 "+e );
            }
        }
    }


    // 初始化请求
    private void initRequest() {
        // 请求数据
        requestDate();
        // 删除文件
        delectFile();
        //删除全部文件
        delectAll();
        //   请求云端要展示文件
        requestCloudList(pager);
        // 获取下载文件的路径请求
        fileDownloadUrl = new NetworkRequest();
        fileDownloadUrl.setmNetworkRequestListener(downloadurl);
        // 下载文件请求
        fileDownload = new NetworkRequest();
        fileDownload.setmIDownloadRequestListenter(downloadfile);
        // 下载xml 文件
        xmlDownload = new NetworkRequest();
        xmlDownload.setmIDownloadRequestListenter(xmlDownloadfile);
    }

    //初始化 请求展示数据
    private void requestCloudList(int pager) {
        mNetworkRequest.requestServerDate(nmcontext, RBConfig.CLUDE_DEVICE_LIST + pager);
    }

    //初始化  请求数据
    private void requestDate() {
        mNetworkRequest = new NetworkRequest();
        mNetworkRequest.setmNetworkRequestListener(mNetworkRequestListener);
        mlist.clear();
    }

    //初始化 删除全部文件
    private void delectAll() {
        delectAllfile = new NetworkRequest();
        delectAllfile.setmNetworkRequestListener(delectAll);
    }

    //初始化 删除文件
    private void delectFile() {
        tNetworkRequest = new NetworkRequest();
        tNetworkRequest.setmNetworkRequestListener(tNetworkRequestListener);
    }

    // todo 请求展示数据------------------------------------
    private NetworkRequestListener mNetworkRequestListener = new NetworkRequestListener() {
        @Override
        public void success(Response response) {
            requestDate(response);
        }

        @Override
        public void fail(String s) {
        }
    };

    // 解析展示请求的数据 todo ----------->
    private void requestDate(Response response) {
        CloudListBean mCloudListBean = (CloudListBean) JsonUitl.NetworkResponseDateDeal(response, CloudListBean.class);
        if (mCloudListBean != null && mCloudListBean.rows != null && mCloudListBean.rows.size() > 0) {
            totlePage = mCloudListBean.getTotal();
            mlist.addAll(mCloudListBean.rows);
            sortingList();                                                                          // 排序
            pager++;
            if(mCloudListBean.rows.size() <5){
                mCloudListAdapter.changeState(2);
            }
        } else {
            mCloudListAdapter.changeState(2);
        }                                                                                     // 加载完成
    }


    //  初始化空间
    public void initSpace(ZzHorizontalProgressBar mfragmentCloudListProgress, Context nmcontext, TextView mtv) {
        // 获取数据库存储的 服务已用空间(单位 GB) serverStoreSpaceUse 和服务存储空间(单位 GB) serverStoreSpace
        DeviceAttributeBeanDaoUtils mDeviceAttributeBeanDaoUtils = new DeviceAttributeBeanDaoUtils(nmcontext);
        List<DeviceAttributeBean> bean = mDeviceAttributeBeanDaoUtils.equery();
        if (bean != null && bean.size() > 0) {
            double user_space = bean.get(0).getServerStoreSpaceUse();
            double all_spce = bean.get(0).getServerStoreSpace();
            int porgress = (int) (user_space / all_spce * 100);                                        // 转化成进度
            mfragmentCloudListProgress.setProgress(porgress);                                       //设置进度
            double free = all_spce - user_space;
            int freespace = (int) (free / 1024);
            mtv.setText("剩余：" + freespace + "GB");
        }
    }


    // todo 点击 发送消息  -------------------------------------                                      点击事件
    @Override
    public void onClickLocal(int pager) {
        iCloudListView.sendMessgeLocal(pager);
    }


    // todo 点击 全部删除 ------------------------------------
    @Override
    public void delectAllFile() {
        //  弹框 提示 确定就去删除全部
        final DeleteFileDialog mDeleteFileDialog = new DeleteFileDialog(nmcontext, "是否删除全部文件", "删除全部文件");
        mDeleteFileDialog.setmIDeleteFileDialogListener(new IDeleteFileDialogListener() {
            @Override
            public void cancel() {
                mDeleteFileDialog.dismiss();
            }

            @Override
            public void confirm() {
                String allFileids = getAllFileIds();                                                //  调用删除全部的接口 删除数据
                requestAllFile(allFileids);                                                         // 删除 全部文件
                mDeleteFileDialog.dismiss();
            }
        });
        mDeleteFileDialog.show();
    }

    // 删除全部数据
    private void requestAllFile(String file_id) {
        delectAllfile.requestServerDate(nmcontext, RBConfig.DELECT_CLUD_FILE + "/" + file_id);
    }

    // 获取所有文件id 字符串 如： 1,2,3
    private String getAllFileIds() {
        String file_ids = "";
        for (int i = 0; i < mlist.size(); i++) {
            if (i < (mlist.size() - 1)) {
                file_ids = file_ids + mlist.get(i).id + ",";
            } else {
                file_ids = file_ids + mlist.get(i).id;
            }
        }
        return file_ids;
    }

    // 删除全部
    private NetworkRequestListener delectAll = new NetworkRequestListener() {
        @Override
        public void success(Response response) {
            delectAllResponse(response);
        }

        @Override
        public void fail(String s) {
        }
    };

    // 删除全部响应
    private void delectAllResponse(Response response) {
        try {
            String NetWorkResponse = response.body().string();
            JSONObject jsonObject = new JSONObject(NetWorkResponse);
            final int code = jsonObject.getInt("code");
            MyClientApplication.getMhandler().post(new Runnable() {
                @Override
                public void run() {
                    if (code == 100) {                                                                        //  处理删除成功
                        mlist.clear();
                        mCloudListAdapter.notifyDataSetChanged();
                    } else {                                                                                  // 失败的操作
                        iCloudListView.showToast("全部删除失败");
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // todo 删除其中某个文件  ------------------------------------                                    2
    private void deleteAmongThemFile(final int postion) {
        final DeleteFileDialog mDeleteFileDialog = new DeleteFileDialog(nmcontext, "删除" + mlist.get(postion).getName(), "删除文件");
        mDeleteFileDialog.setmIDeleteFileDialogListener(new IDeleteFileDialogListener() {
            @Override
            public void cancel() {
                mDeleteFileDialog.dismiss();
            }

            @Override
            public void confirm() {
                if (postion <= (mlist.size() - 1)) {
                    mpostion = postion;
                    String file_id = mlist.get(postion).id;
                    requestFileDelect(file_id);                                                     //  请求网络
                } else {
                }
                mDeleteFileDialog.dismiss();
            }
        });
        mDeleteFileDialog.show();
    }

    // 删除
    private void requestFileDelect(String file_id) {
        tNetworkRequest.requestServerDate(nmcontext, RBConfig.DELECT_CLUD_FILE + "/" + file_id);
        Log.e(TAG, "requestFileDelect 删除 : "+ RBConfig.DELECT_CLUD_FILE + "/" + file_id);
    }

    // 删除数据
    private NetworkRequestListener tNetworkRequestListener = new NetworkRequestListener() {
        @Override
        public void success(Response response) {
            delectSingleFile(response);
        }

        @Override
        public void fail(String s) {
        }
    };

    // 删除单个文件
    private void delectSingleFile(Response response) {
        try {
            String NetWorkResponse = response.body().string();
            Log.e(TAG, "delectSingleFile NetWorkResponse : "+NetWorkResponse );
            JSONObject jsonObject = new JSONObject(NetWorkResponse);
            final int code = jsonObject.getInt("code");
            Log.e(TAG, "delectSingleFile code : "+code );
            // todo 主线程中更新ui
            MyClientApplication.getMhandler().post(new Runnable() {
                @Override
                public void run() {
                    if (code == 100) {                                                                        //  处理删除成功
                        mlist.remove(mpostion);
                        mCloudListAdapter.notifyDataSetChanged();
                    } else {                                                                                   // 失败的操作     提示哪个文件删除失败 要指明文件的文件名
                        iCloudListView.showToast("删除" + mlist.get(mpostion).getName() + "失败");
                    }
                }
            });

        } catch (Exception e) {
            Log.e(TAG, "delectSingleFile code =======: "+e );
        }
    }


    // todo 点击 倒序排序   ------------------------------------
    @Override
    public void sortingList() {
        if (flage) {
            flage = false;
            Reverse();
        } else {
            flage = true;
            order();
        }
    }

    // 顺序
    private void order() {
        Collections.sort(mlist, new Comparator<CloudListBean.RowsBean>() {
            @Override
            public int compare(CloudListBean.RowsBean rowsBean, CloudListBean.RowsBean rowsBean2) {
                return (int) (rowsBean.getCreateTime() - rowsBean2.getCreateTime());
            }
        });
        mCloudListAdapter.updateDate(mlist);
    }

    // 倒序
    private void Reverse() {
        Collections.sort(mlist, new Comparator<CloudListBean.RowsBean>() {
            @Override
            public int compare(CloudListBean.RowsBean rowsBean, CloudListBean.RowsBean rowsBean2) {
                return (int) (rowsBean2.getCreateTime() - rowsBean.getCreateTime());
            }
        });
        mCloudListAdapter.updateDate(mlist);
    }
}
